package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
public class CacheClient {

    // 封装redis工具类
    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 写入任意对象到redis
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    // 写入任意对象到redis带逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        // 设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        // 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    // 封装缓存穿透
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack,
                                           Long time, TimeUnit unit) {
        // 1.在Redis中查询商铺信息
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2.存在，返回商铺信息
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        // 3.判断命中的是否是空值""
        if(json != null){
            return null;
        }
        // 4.不存在，在数据库中查询
        R r = dbFallBack.apply(id);
        // 5.不存在，在redis中存入空值，返回错误信息  缓存穿透--缓存空值
        if(r == null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        // 6.存在，存储信息到Redis中
        this.set(key,r,time+ RandomUtil.randomLong(0,10),unit);
        // 7.返回商铺信息
        return r;
    }

    // 封装逻辑过期
    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack,
                                            Long time, TimeUnit unit) {
        // 1.在Redis中查询商铺信息
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2.未命中，返回空
        if (StrUtil.isBlank(json)) {
            return null;
        }
        // 3.命中，判断逻辑是否过期
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        // 3.1 未过期，返回数据
        R r = BeanUtil.toBean(redisData.getData(),type);
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())){
            return r;
        }
        // 4.过期,重建缓存
        // 4.1 尝试获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 4.2 获取到锁，开启独立线程
            // DoubleCheck 缓存是否过期
            String json2 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isBlank(json2)) {
                return null;
            }
            RedisData redisData2 = JSONUtil.toBean(json2, RedisData.class);
            R r1 = BeanUtil.toBean(redisData.getData(),type);
            if (redisData2.getExpireTime().isAfter(LocalDateTime.now())){
                return r1;
            }
            // 开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    // 查询数据库
                    R r2 = dbFallBack.apply(id);
                    // 重建缓存
                    this.setWithLogicalExpire(key, r2, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
        }
        // 4.4 没获取到锁，返回旧数据
        return r;
    }

    // 获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    // 释放锁
    private void unLock(String key){
        Boolean flag = stringRedisTemplate.delete(key);
    }
}
